package com.apkicon.parser;

import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import net.dongliu.apk.parser.bean.UseFeature;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 使用apk-parser库的APK解析器
 * 正确解析AndroidManifest.xml和获取准确的图标路径
 */
public class ApkParserLibrary {
    
    /**
     * 使用apk-parser解析APK文件
     */
    public static ApkInfo parseApkWithLibrary(File apkFile) throws Exception {
        System.out.println("🔍 使用apk-parser解析APK: " + apkFile.getName());
        
        try (ApkFile apk = new ApkFile(apkFile)) {
            // 解析APK元数据
            ApkMeta apkMeta = apk.getApkMeta();
            
            System.out.println("📱 应用信息:");
            System.out.println("   包名: " + apkMeta.getPackageName());
            System.out.println("   版本: " + apkMeta.getVersionName() + " (" + apkMeta.getVersionCode() + ")");
            System.out.println("   应用名称: " + apkMeta.getLabel());
            
            // 获取图标信息
            String iconPath = apkMeta.getIcon();
            System.out.println("🎯 图标路径: " + iconPath);
            
            if (iconPath == null || iconPath.isEmpty()) {
                throw new Exception("No icon found in AndroidManifest.xml");
            }
            
            // 解析图标资源
            IconResource iconResource = resolveIconResource(apk, iconPath);
            if (iconResource == null) {
                throw new Exception("Unable to resolve icon resource: " + iconPath);
            }
            
            // 检查是否有Adaptive Icon
            boolean hasAdaptiveIcon = false; // apk-parser可能不支持Adaptive Icon检测
            if (hasAdaptiveIcon) {
                System.out.println("🔍 发现Adaptive Icon");
            }
            
            // 创建应用图标信息
            AppIconInfo appIconInfo = new AppIconInfo(iconPath, null, hasAdaptiveIcon);
            
            return new ApkInfo(apkFile, iconResource, appIconInfo);
        }
    }
    
    /**
     * 解析图标资源
     */
    private static IconResource resolveIconResource(ApkFile apk, String iconPath) throws IOException {
        System.out.println("🔍 解析图标资源: " + iconPath);
        
        // 尝试直接读取图标文件
        byte[] iconData = apk.getFileData(iconPath);
        if (iconData != null) {
            System.out.println("✅ 找到图标文件: " + iconPath + " (" + iconData.length + " bytes)");
            
            // 确定图标类型
            String iconType = determineIconType(iconPath, iconData);
            int iconSize = estimateIconSize(iconPath);
            String density = extractDensityFromPath(iconPath);
            
            return new IconResource(iconPath, iconType, iconSize, density);
        }
        
        // 如果直接路径找不到，尝试在资源目录中查找
        return findIconInResources(apk, iconPath);
    }
    
    /**
     * 在资源目录中查找图标
     */
    private static IconResource findIconInResources(ApkFile apk, String iconPath) throws IOException {
        System.out.println("🔍 在资源目录中查找图标...");
        
        // 从图标路径中提取资源名称
        String resourceName = extractResourceName(iconPath);
        System.out.println("🔍 资源名称: " + resourceName);
        
        // 按密度优先级查找
        String[] densities = {"xxxhdpi", "xxhdpi", "xhdpi", "hdpi", "mdpi", "ldpi"};
        
        for (String density : densities) {
            // 查找PNG图标
            String pngPath = "res/mipmap-" + density + "/" + resourceName + ".png";
            byte[] pngData = apk.getFileData(pngPath);
            if (pngData != null) {
                System.out.println("✅ 找到PNG图标: " + pngPath);
                return new IconResource(pngPath, "png", getSizeForDensity(density), density);
            }
            
            // 查找WebP图标
            String webpPath = "res/mipmap-" + density + "/" + resourceName + ".webp";
            byte[] webpData = apk.getFileData(webpPath);
            if (webpData != null) {
                System.out.println("✅ 找到WebP图标: " + webpPath);
                return new IconResource(webpPath, "webp", getSizeForDensity(density), density);
            }
            
            // 查找XML图标
            String xmlPath = "res/mipmap-" + density + "/" + resourceName + ".xml";
            byte[] xmlData = apk.getFileData(xmlPath);
            if (xmlData != null) {
                System.out.println("✅ 找到XML图标: " + xmlPath);
                return new IconResource(xmlPath, "xml", getSizeForDensity(density), density);
            }
        }
        
        // 查找drawable目录
        for (String density : densities) {
            String drawablePath = "res/drawable-" + density + "/" + resourceName + ".png";
            byte[] drawableData = apk.getFileData(drawablePath);
            if (drawableData != null) {
                System.out.println("✅ 找到drawable图标: " + drawablePath);
                return new IconResource(drawablePath, "png", getSizeForDensity(density), density);
            }
        }
        
        System.out.println("❌ 未找到图标资源");
        return null;
    }
    
    /**
     * 从图标路径中提取资源名称
     */
    private static String extractResourceName(String iconPath) {
        // 处理@mipmap/ic_launcher格式
        if (iconPath.startsWith("@")) {
            return iconPath.substring(iconPath.lastIndexOf("/") + 1);
        }
        
        // 处理直接路径
        String fileName = iconPath.substring(iconPath.lastIndexOf("/") + 1);
        if (fileName.contains(".")) {
            return fileName.substring(0, fileName.lastIndexOf("."));
        }
        
        return fileName;
    }
    
    /**
     * 确定图标类型
     */
    private static String determineIconType(String iconPath, byte[] iconData) {
        if (iconPath.endsWith(".png")) {
            return "png";
        } else if (iconPath.endsWith(".webp")) {
            return "webp";
        } else if (iconPath.endsWith(".xml")) {
            // 对于XML文件，使用更精确的类型判断
            return determineXmlIconType(iconPath, iconData);
        } else if (iconData.length > 4) {
            // 通过文件头判断
            if (iconData[0] == (byte) 0x89 && iconData[1] == 0x50 && iconData[2] == 0x4E && iconData[3] == 0x47) {
                return "png";
            } else if (iconData[0] == 0x52 && iconData[1] == 0x49 && iconData[2] == 0x46 && iconData[3] == 0x46) {
                return "webp";
            }
        }
        
        return "unknown";
    }
    
    /**
     * 确定XML图标类型
     */
    private static String determineXmlIconType(String iconPath, byte[] iconData) {
        try {
            String xmlContent = new String(iconData, "UTF-8");
            
            // 1. 优先检查Adaptive Icon
            if (xmlContent.contains("<adaptive-icon") || xmlContent.contains("adaptive-icon")) {
                System.out.println("🔍 检测到Adaptive Icon");
                return "adaptive";
            }
            
            // 2. 检查Vector Drawable
            if (xmlContent.contains("<vector") || xmlContent.contains("vector")) {
                System.out.println("🔍 检测到Vector Drawable");
                return "vector";
            }
            
            // 3. 检查Bitmap Drawable
            if (xmlContent.contains("<bitmap") || xmlContent.contains("bitmap")) {
                System.out.println("🔍 检测到Bitmap Drawable");
                return "bitmap";
            }
            
            // 4. 检查Shape Drawable
            if (xmlContent.contains("<shape") || xmlContent.contains("shape")) {
                System.out.println("🔍 检测到Shape Drawable");
                return "shape";
            }
            
            // 5. 默认情况
            System.out.println("🔍 XML类型未知，默认为vector");
            return "vector";
            
        } catch (Exception e) {
            System.out.println("🔍 XML解析失败，默认为vector: " + e.getMessage());
            return "vector";
        }
    }
    
    /**
     * 判断是否为Vector Drawable
     * 按照Android原生逻辑：先检查是否为Adaptive Icon，再检查是否为Vector Drawable
     */
    private static boolean isVectorDrawable(String iconPath, byte[] iconData) {
        if (iconPath == null || !iconPath.endsWith(".xml")) {
            return false;
        }
        
        try {
            // 获取XML内容来确定实际类型
            String xmlContent = new String(iconData, "UTF-8");
            if (xmlContent == null) {
                return false;
            }
            
            // 检查是否为Adaptive Icon (如果是，则不是Vector Drawable)
            if (xmlContent.contains("<adaptive-icon") || xmlContent.contains("adaptive-icon")) {
                return false;
            }
            
            // 检查是否为Vector Drawable
            return xmlContent.contains("<vector") || xmlContent.contains("vector");
            
        } catch (Exception e) {
            System.out.println("🔍 XML解析失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 分析XML图标类型
     */
    private static String analyzeXmlIconType(byte[] xmlData) {
        try {
            // 尝试将二进制XML转换为字符串进行分析
            String xmlContent = new String(xmlData, "UTF-8");
            
            // 检查是否是Adaptive Icon (优先级最高)
            if (xmlContent.contains("<adaptive-icon") || xmlContent.contains("adaptive-icon")) {
                System.out.println("🔍 检测到Adaptive Icon");
                return "adaptive";
            }
            
            // 检查是否是Vector Drawable
            if (xmlContent.contains("<vector") || xmlContent.contains("vector")) {
                System.out.println("🔍 检测到Vector Drawable");
                return "vector";
            }
            
            // 检查是否是Bitmap Drawable
            if (xmlContent.contains("<bitmap") || xmlContent.contains("bitmap")) {
                System.out.println("🔍 检测到Bitmap Drawable");
                return "bitmap";
            }
            
            // 检查是否是Shape Drawable
            if (xmlContent.contains("<shape") || xmlContent.contains("shape")) {
                System.out.println("🔍 检测到Shape Drawable");
                return "shape";
            }
            
            System.out.println("🔍 XML类型未知，默认为vector");
            return "vector"; // 默认为vector drawable
            
        } catch (Exception e) {
            System.out.println("🔍 XML解析失败，默认为vector: " + e.getMessage());
            return "vector"; // 解析失败时默认为vector drawable
        }
    }
    
    /**
     * 估算图标尺寸
     */
    private static int estimateIconSize(String iconPath) {
        String density = extractDensityFromPath(iconPath);
        return getSizeForDensity(density);
    }
    
    /**
     * 从路径中提取密度信息
     */
    private static String extractDensityFromPath(String path) {
        String[] densities = {"xxxhdpi", "xxhdpi", "xhdpi", "hdpi", "mdpi", "ldpi"};
        for (String density : densities) {
            if (path.contains("-" + density + "/")) {
                return density;
            }
        }
        return "mdpi"; // 默认密度
    }
    
    /**
     * 根据密度获取对应的图标尺寸
     */
    private static int getSizeForDensity(String density) {
        switch (density) {
            case "ldpi": return 36;
            case "mdpi": return 48;
            case "hdpi": return 72;
            case "xhdpi": return 96;
            case "xxhdpi": return 144;
            case "xxxhdpi": return 192;
            default: return 48;
        }
    }
    
    /**
     * APK信息
     */
    public static class ApkInfo {
        private final File apkFile;
        private final IconResource iconResource;
        private final AppIconInfo appIconInfo;
        
        public ApkInfo(File apkFile, IconResource iconResource, AppIconInfo appIconInfo) {
            this.apkFile = apkFile;
            this.iconResource = iconResource;
            this.appIconInfo = appIconInfo;
        }
        
        public File getApkFile() { return apkFile; }
        public IconResource getIconResource() { return iconResource; }
        public AppIconInfo getAppIconInfo() { return appIconInfo; }
        
        public String getIconPath() { return iconResource.getPath(); }
        public String getIconType() { return iconResource.getType(); }
        public int getIconSize() { return iconResource.getSize(); }
        public String getIconDensity() { return iconResource.getDensity(); }
        public boolean hasAdaptiveIcon() { return appIconInfo.hasAdaptiveIcon(); }
        public String getIconReference() { return appIconInfo.getIconRef(); }
    }
    
    /**
     * 应用图标信息
     */
    public static class AppIconInfo {
        private final String iconRef;
        private final String adaptiveIconRef;
        private final boolean hasAdaptiveIcon;
        
        public AppIconInfo(String iconRef, String adaptiveIconRef, boolean hasAdaptiveIcon) {
            this.iconRef = iconRef;
            this.adaptiveIconRef = adaptiveIconRef;
            this.hasAdaptiveIcon = hasAdaptiveIcon;
        }
        
        public String getIconRef() { return iconRef; }
        public String getAdaptiveIconRef() { return adaptiveIconRef; }
        public boolean hasAdaptiveIcon() { return hasAdaptiveIcon; }
        
        public String getResourceName() {
            if (iconRef.startsWith("@")) {
                return iconRef.substring(iconRef.lastIndexOf("/") + 1);
            }
            return iconRef;
        }
        
        public String getResourceType() {
            if (iconRef.startsWith("@")) {
                String[] parts = iconRef.substring(1).split("/");
                return parts.length > 0 ? parts[0] : "drawable";
            }
            return "drawable";
        }
    }
    
    /**
     * 图标资源
     */
    public static class IconResource {
        private final String path;
        private final String type;
        private final int size;
        private final String density;
        
        public IconResource(String path, String type, int size, String density) {
            this.path = path;
            this.type = type;
            this.size = size;
            this.density = density;
        }
        
        public String getPath() { return path; }
        public String getType() { return type; }
        public int getSize() { return size; }
        public String getDensity() { return density; }
        
        @Override
        public String toString() {
            return String.format("IconResource{path='%s', type='%s', size=%d, density='%s'}", 
                               path, type, size, density);
        }
    }
}
